// pages/sent-flowers/sent-flowers.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    // 统计数据
    totalSent: 0,
    todaySent: 0,
    matchedCount: 0,
    
    // 记录列表
    recordList: [],
    
    // 分页信息
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad(options) {
    console.log('送出的花页面加载');
    this.loadData();
  },

  onShow() {
    console.log('送出的花页面显示');
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.refreshData();
  },

  onReachBottom() {
    console.log('上拉加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreData();
    }
  },

  // 加载数据
  async loadData() {
    try {
      await Promise.all([
        this.loadStatistics(),
        this.loadRecordList()
      ]);
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },

  // 加载统计数据
  async loadStatistics() {
    try {
      // 从API加载统计数据
      const response = await api.getSentFlowerStats();
      
      const stats = response && response.code === 0 ? response.data : {
        totalSent: 0,
        todaySent: 0,
        matchedCount: 0
      };
      
      this.setData(stats);
      
    } catch (error) {
      console.error('加载统计数据失败:', error);
      throw error;
    }
  },

  // 加载记录列表
  async loadRecordList() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const { pageNum, pageSize } = this.data;
      
      // 从API加载送花记录
      const response = await api.getSentFlowerRecords({
        pageNum: pageNum,
        pageSize: pageSize
      });
      
      if (response && response.code === 0 && response.data) {
        const records = response.data.recordList || [];
        
        if (pageNum === 1) {
          this.setData({ recordList: records });
        } else {
          this.setData({ 
            recordList: [...this.data.recordList, ...records] 
          });
        }

        this.setData({
          hasMore: records.length === pageSize,
          pageNum: pageNum + 1
        });
      }

    } catch (error) {
      console.error('加载记录列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },


  // 刷新数据
  refreshData() {
    this.setData({ 
      pageNum: 1,
      recordList: [],
      hasMore: true
    });
    this.loadData();
  },

  // 加载更多数据
  loadMoreData() {
    this.loadRecordList();
  },

  // 记录项点击
  onRecordTap(e) {
    const user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: `/pages/profile/profile?userNum=${user.userNum}`
    });
  },

  // 联系用户
  onContactUser(e) {
    e.stopPropagation();
    const user = e.currentTarget.dataset.user;
    
    wx.showModal({
      title: '联系TA',
      content: `您与${user.name}匹配成功！请联系管理员进行线下牵线。\n\n管理员微信：yuanlaixiangyu_admin`,
      confirmText: '复制微信号',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.setClipboardData({
            data: 'yuanlaixiangyu_admin',
            success: () => {
              wx.showToast({
                title: '已复制到剪贴板',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  // 去首页
  onGoToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '等待',
      'matched': '匹配',
      'expired': '过期'
    };
    return statusMap[status] || '未知';
  },

  // 获取操作文本
  getActionText(status) {
    const actionMap = {
      'pending': '等待回应',
      'matched': '匹配成功',
      'expired': '已过期'
    };
    return actionMap[status] || '未知状态';
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我的送花记录 - 青鸟传信',
      path: '/pages/index/index',
      imageUrl: '/assets/images/share-image.png'
    };
  }
});